package com.yenlien.traceyun.control.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.dao.CompanyModelCategoryDao;
import com.yenlien.traceyun.control.dao.CompanyModelClassifyDao;
import com.yenlien.traceyun.control.dao.ModelCategoryDao;
import com.yenlien.traceyun.control.dao.ModelClassifyDao;
import com.yenlien.traceyun.control.entity.CompanyModelCategory;
import com.yenlien.traceyun.control.entity.CompanyModelClassify;
import com.yenlien.traceyun.control.service.rest.ResourceRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-11-02
 * @description:
 **/

@Service
public class CompanyMenuService {

    @Autowired
    private ResourceRestService resourceRestService;


    @Autowired
    private CompanyModelCategoryDao companyModelCategoryDao;


    @Autowired
    private ModelCategoryDao modelCategoryDao;

    /**
     * 设置企业菜单和模型分类
     *
     * @param params
     * @return
     */
    @Transactional()
    public Object setCommpany(JSONObject params) {
        JSONArray modelclass = params.getJSONArray("categories");
        String companyId = params.getString("companyId");
        companyModelCategoryDao.deleteByCompanyId(companyId);
        if (modelclass != null && modelclass.size() > 0) {
            List<CompanyModelCategory> cms = new ArrayList<>();
            for (int i = 0; i < modelclass.size(); i++) {
                CompanyModelCategory companyModelClassify = new CompanyModelCategory();
                companyModelClassify.setCompanyId(companyId);
                companyModelClassify.setCategoryId(modelclass.getString(i));
                cms.add(companyModelClassify);
            }
            companyModelCategoryDao.saveAll(cms);
        }
        return resourceRestService.setCompanyAppMenu(params);
    }

    /**
     * 根据公司id加载分类
     *
     * @param companyId
     * @return
     */
    public Object loadCategory(String companyId) {
        return modelCategoryDao.findRootByCompanyId(companyId);
    }
}
